﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using System.IO;
using System.Xml.Linq;
using System.Xml.Serialization;
using System.Text.RegularExpressions;

namespace m10cde_WinForms.Hiscore
{
    /// <summary>
    /// input:  class takes in raw data, saves data as xml to scores.xml
    /// output: outputs raw data parsed from xml file
    /// </summary>
    class Hiscore
    {

        /// <summary>
        /// empty constructor
        /// </summary>
        public Hiscore()
        {
        }

        /// <summary>
        /// Working version of the addscore method
        /// utilises the LINQ to XML module XElement
        /// </summary>
        /// <param name="name"></param>
        /// <param name="score"></param>
        public void addScore(String name, int score)
        {
            Score myScoreObject = new Score();
            myScoreObject.name = name;
            myScoreObject.score = score.ToString(); //create a score object and populate it with the paramaters passed into the method
            /// TODO pass a shape object instead of parameters

            string fileLocation = "../../Hiscore/Scores.xml";   //set the fileLocation var to be the location of the xml file

            if (!File.Exists(fileLocation )){       // if the file does not exist, create it and add in the root tag "Scores"
                XmlTextWriter myWriter = new XmlTextWriter(fileLocation, null);
                myWriter.WriteStartElement("Scores");
                myWriter.WriteEndElement();
                myWriter.Close();
            }

            XElement xml = XElement.Load(fileLocation);
            xml.Add(new XElement("Record",
                    new XElement("Name", myScoreObject.name),
                    new XElement("Score", myScoreObject.score),
                    new XElement("Date", myScoreObject.date)));
            xml.Save(fileLocation);
        }


        /// <summary>
        /// reads xml data from xml file score.xml and outputs a string.
        /// </summary>
        /// <returns>a long string of all xml values</returns>
        public String getScoreTable()
        {
            String formattedOutputString = "Name  " + "Score  " + "     Date   " + System.Environment.NewLine;
            XDocument myDoc = XDocument.Load("../../Hiscore/Scores.xml");
            var scores = from record in myDoc.Descendants("Record")
                         select new{
                             name = record.Element("Name").Value,
                             score = record.Element("Score").Value,
                             date = record.Element("Date").Value,
                         };
                         
            List<Score> scoreList = new List<Score>();

            foreach (var record in scores){
                Score myScore = new Score(record.name, record.score);  // create an object
                scoreList.Add(myScore);
            }

            scoreList.Sort();    //sort list by score size, biggest first
            foreach (Score x in scoreList){
                formattedOutputString += x.toString();
            }

            return formattedOutputString;
        }

        /*        public void addScoreV1(String name, int score){
                    DateTime myDate = DateTime.Today;   //create a var with todays date and time in it

                    XmlDocument myDoc = new XmlDocument();  //create a var of type xmldocument, this allows us to interact with it using built in vs2010 methods
                    myDoc.Load("../../Hiscore/Scores.xml"); // the ../../ is used to jump up 2 directory levels, otherwise it defaults to bin/debug/

                    XmlElement myNameElement = myDoc.CreateElement("name");
                    myNameElement.InnerText = name;
                    myDoc.DocumentElement.AppendChild(myNameElement);

                    XmlElement myScoreElement = myDoc.CreateElement("score");
                    myScoreElement.InnerText = score.ToString();
                    myDoc.DocumentElement.AppendChild(myScoreElement);

                    XmlElement myDateElement = myDoc.CreateElement("date");
                    myDateElement.InnerText = myDate.ToString();
                    myDoc.DocumentElement.AppendChild(myDateElement);

                    myDoc.PreserveWhitespace = true;
            
                    myDoc.Save("../../Hiscore/Scores.xml");
                }   

        public void addScoreV2(String name, int score)
        {
            Score myScoreObject = new Score();
            myScoreObject.name = name;
            myScoreObject.score = score.ToString();
            List<Score> myScoreList = new List<Score>() { myScoreObject };

            XmlSerializer mySerializer = new XmlSerializer(typeof(List<Score>));

            TextWriter WriteFileStream = new StreamWriter(@"../../Hiscore/Scores.xml", true); // Create a new file stream to write the serialized object to a file, append mode is set to true
            mySerializer.Serialize(WriteFileStream, myScoreList);
            WriteFileStream.Close();    //end stream
        }

        public void addScoreV1(String name, int score)
        {
            DateTime myDate = DateTime.Today;   //create a var with todays date and time in it

            XmlDocument myDoc = new XmlDocument();  //create a var of type xmldocument, this allows us to interact with it using built in vs2010 methods
            myDoc.Load("../../Hiscore/Scores.xml"); // the ../../ is used to jump up 2 directory levels, otherwise it defaults to bin/debug/

            XmlNode rootNode = myDoc.CreateElement("scores");
            myDoc.AppendChild(rootNode);

            XmlNode personNode = myDoc.CreateElement("person");
            myDoc.AppendChild(personNode);

            XmlNode nameNode = myDoc.CreateElement("name");
            nameNode.InnerText = name;

            XmlNode scoreNode = myDoc.CreateElement("score");
            nameNode.InnerText = score.ToString();

            XmlNode dateNode = myDoc.CreateElement("date");
            nameNode.InnerText = myDate.ToString();

            personNode.AppendChild(personNode);
            myDoc.PreserveWhitespace = true;

            myDoc.Save("../../Hiscore/Scores.xml");
        } */
    }
}